<?php

// +----------------------------------------------------------------------
// | Admin Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-admin
// | github 代码仓库：https://github.com/zoujingli/think-plugs-admin
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\paths\controller;

use app\common\model\paths\ClassModel;
use app\common\model\paths\ClassTaskModel;
use app\common\model\paths\PlatformModel;
use app\common\model\paths\TaskModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemUser;

/**
 * 课程和班级
 * @class Base
 * @package app\admin\controller
 */
class ClassTask extends Controller
{
    /**
     * 班级和课程
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index ()
    {
        $class_id = $this->request->get('class_id');

        $task_arr = TaskModel::mk()->field('title,id')->where('1=1')->select();

        $task_ids = ClassTaskModel::where('class_id', $class_id)->column('task_id');

        foreach ($task_arr as &$item) {
            $item['is_check'] = in_array($item['id'], $task_ids);
        }

        $this->class_id = $class_id;
        $this->task_arr = $task_arr;
        $this->fetch();

    }

    /**
     * 课程选中
     *
     * @return void
     */
    public function change()
    {
        $task_id   = $this->request->post('task_id');
        $status    = $this->request->post('status');
        $class_id  = $this->request->post('class_id');


        if ($status == 1) {
            $class_task = ClassTaskModel::mk()->where('task_id',$task_id)->where('class_id', $class_id)->find();

            if (!$class_task) {

                $class_obj = ClassModel::mk()->where('id', $class_id)->find();

                $class_task = new ClassTaskModel();
                $class_task->task_id  = $task_id;
                $class_task->class_id = $class_id;
                $class_task->user_id  = $class_obj->user_id;
                $class_task->platform_id = $class_obj->account_id;
                $class_task->save();
            }

        } else {
            ClassTaskModel::mk()->where('task_id',$task_id)->where('class_id', $class_id)->delete();
        }

        $this->success('成功');
    }
}